package br.pucrio.inf.aaaong.models.database.exceptions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PostgreSQLConstraintException extends Exception {

	private String constraintName;

	public PostgreSQLConstraintException(String constraintName) {
		this.constraintName = constraintName;
	}

	public static boolean isConstraintViolationCode(String sqlStateCode) {
		return sqlStateCode.startsWith("23");
	}

	public static PostgreSQLConstraintException fromExceptionMessage(String exceptionMsg) {
		String constraintName = extractConstraintName(exceptionMsg);
		return new PostgreSQLConstraintException(constraintName);
	}

	public static String extractConstraintName(String exceptionMsg) {
		Pattern regexp = Pattern.compile("constraint \"([^\"]+)");
		Matcher matcher = regexp.matcher(exceptionMsg);
		if (matcher.find()) {
			String constraintName = matcher.group(1);
			return constraintName;
		} else {
			throw new RuntimeException("Unrecognized SQL exception message '" + exceptionMsg + "'");
		}
	}

	public String getConstraintName() {
		return constraintName;
	}
}
